<?php

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;

use app\admin\model\BotGroupmember;
use app\admin\model\BotMember;
use app\common\model\tpzs\Gather;
use app\constants\Bot;

class Tpzsgather extends Botbase
{
    /**
     * @var Gather
     */
    protected $model;
    /**
     * @var BotGroupmember
     */
    private $groupMemberM;
    /**
     * @var BotMember
     */
    private $memberM;
    /**
     * @var array
     */
    private $tabList;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new Gather();
        $this->groupMemberM = new BotGroupmember();
        $this->memberM = new BotMember();
        $this->tabList = [
            'index' => ['title' => '采品群', 'href' => url('index')],
            'group' => ['title' => '普通群', 'href' => url('group')],
        ];
    }

    /**
     *
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = ['g.bot_id' => $this->bot['id'], 'g.admin_id' => $this->adminInfo['id']];
            $params = [
                'alias' => 'g',
                'join' => [
                    ['bot_member m', 'm.id=g.group_id']
                ],
                'where' => $where,
                'refresh' => true
            ];
            $total = $this->model->totalJoin($params);
            if ($total) {
                $list = $this->model->getListJoin(array_merge($params, [
                    'limit' => [$post_data['page'], $post_data['limit']],
                    'field' => ['g.id','m.nickname as group_title', 'g.officer', 'm.id as group_id','g.status','g.wxids']
                ]));
                foreach ($list as $k => $v){
                    $group_members = $this->groupMemberM->getField(['nickname'], ['wxid' => ['in', $v['officer']], 'group_id' => $v['group_id']]);
                    $v['officer_names'] = implode(',', $group_members);
                    $list[$k] = $v;
                }
            }else{
                $list = [];
            }
            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }
        $builder = new ListBuilder();
        $builder->setTabNav($this->tabList, 'index')
            ->setTip("要新增采品群，请点击普通群选项卡")
                ->addTableColumn(['title' => '序号', 'field' => 'id', 'type' => 'index','minWidth' => 70])
                ->addTableColumn(['title' => '群聊', 'field' => 'group_title', 'minWidth' => 150])
                ->addTableColumn(['title' => '指挥官', 'field' => 'officer_names', 'minWidth' => 200])
                ->addTableColumn(['title' => '发送对象', 'field' => 'wxids', 'minWidth' => 200])
                ->addTableColumn(['title' => '状态', 'field' => 'status', 'type' => 'enum', 'options' => [0 => '禁用', 1 => '启用'],'minWidth' => 60])
                ->addTableColumn(['title' => '操作', 'minWidth' => 70, 'type' => 'toolbar'])
                ->addRightButton('edit');
        return $builder->show();
    }

    /**
     *
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function group()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = ['m.uin' => $this->bot['uin'], 'm.type' => Bot::GROUP, 'g.officer' => ['=', null]];
            !empty($post_data['search_key']) && $where['m.nickname'] = ['like', '%' . $post_data['search_key'] . '%'];
            $params = [
                'alias' => 'm',
                'join' => [
                    ['tpzs_gather g', 'm.id=g.group_id', 'left']
                ],
                'where' => $where,
                'refresh' => true
            ];
            $total = $this->memberM->totalJoin($params);
            $sql = $this->memberM->getLastSql();
            if ($total) {
                $list = $this->memberM->getListJoin(array_merge($params, [
                    'limit' => [$post_data['page'], $post_data['limit']],
                    'field' => ['m.nickname as group_title', 'm.id']
                ]));
            }else{
                $list = [];
            }
            $this->success('success', '', ['total' => $total, 'list' => $list, 'sql' => $sql]);
        }

        $builder = new ListBuilder();
        $builder->setTabNav($this->tabList, 'group')
            ->setSearch([
                ['type' => 'text', 'name' => 'search_key', 'title' => '关键词']
            ])
            ->addTableColumn(['title' => '序号', 'field' => 'id', 'type' => 'index','width' => 60])
            ->addTableColumn(['title' => '群聊', 'field' => 'group_title', 'minWidth' => 150])
            ->addTableColumn(['title' => '操作', 'minWidth' => 70, 'type' => 'toolbar'])
            ->addRightButton('edit', ['title' => '设为采品群', 'href' => url('add', ['group_id' => '__data_id__'])]);
        return $builder->show();
    }

    public function add(){
        $group_id = input('group_id', 0);
        $group = $this->memberM->getOne($group_id);
        //$this->groupMemberM->pullMembers($this->bot, $group);
        $data = ['bot_id' => $this->bot['id'], 'group_id' => $group_id];
        $members = $this->groupMemberM->getField('wxid,nickname',['group_id' => $group_id], true);
        $builder = new FormBuilder();
        $builder->setTip("调度群：所有发单机器人集合群，选品人员把商品素材发到此群，那么群里的所有机器人会采集然后转发各自负责的群。")
            ->setPostUrl(url('savePost'))
            ->addFormItem('bot_id', 'hidden', 'bot_id', 'bot_id')
            ->addFormItem('group_id', 'hidden', '选择调度群', '选择调度群')
            ->addFormItem('officer', 'chosen_multi', '指挥官', '该微信发表的消息才会被转发', $members, 'required')
            ->addFormItem('wxids', 'chosen_multi', '转发到', '消息接收方', $this->getMembers(), 'required')
            ->addFormItem('universal', 'radio', '需要转链', '需要转链', [1=>'是', 0 => '否'], 'required')
            ->setFormData($data);
        return $builder->show();
    }

    public function edit(){
        $id = input('id', null);
        $data = $this->model->getOne($id);

        if (!$data) {
            $this->error('参数错误');
        }
        $data['wxids'] = explode(',', $data['wxids']);
        $data['officer'] = explode(',', $data['officer']);
        $members = $this->groupMemberM->getField('wxid,nickname',['group_id' => $data['group_id']], true);
        $builder = new FormBuilder();
        $builder->setTip("调度群：所有发单机器人集合群，选品人员把商品素材发到此群，那么群里的所有机器人会采集然后转发各自负责的群。")
            ->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('officer', 'chosen_multi', '指挥官', '该微信发表的消息才会被转发', $members, 'required')
            ->addFormItem('wxids', 'chosen_multi', '转发到', '消息接收方', $this->getMembers(), 'required')
            ->addFormItem('universal', 'radio', '需要转链', '需要转链', [1=>'是', 0 => '否'], 'required')
            ->addFormItem('status', 'radio', '状态', '状态', [1=>'启用', 0 => '禁用'], 'required')
            ->setFormData($data);
        return $builder->show();
    }

    public function savePost($jump_to = '/undefined', $data = [])
    {
        $post_data = input('post.');
        $post_data['admin_id'] = $this->adminInfo['id'];
        if(empty($post_data[$this->pk])){
            $res = $this->model->addOne($post_data);
        }else {
            $res = $this->model->updateOne($post_data);
        }
        if($res){
            $group = model('admin/botMember')->getOne($res['group_id']);
            $this->model->getGather([
                'group_wxid' => $group['wxid'],
                'from_wxid' => $res['officer'],
                'bot_wxid' => $this->bot['uin'],
                'refresh' => true
            ]);
            $this->success('数据保存成功', $jump_to);
        }else{
            $this->error('数据保存出错');
        }
    }
}